package br.com.rapidrest.demo.service;

import java.io.Serializable;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import org.jboss.annotation.ejb.LocalBinding;

import br.com.rapidrest.demo.domain.PhoneBook;
import br.com.rapidrest.demo.domain.PhoneEntry;

@Stateless
@LocalBinding(jndiBinding = "PhoneBookServiceBean/local")
public class PhoneBookServiceBean implements PhoneBookService, Serializable {

	private static final long serialVersionUID = -2712577529909870181L;

	@PersistenceContext(unitName = "demo-pu")
	private EntityManager em;

	@Override
	public void savePhoneBook(PhoneBook phoneBook) {
		em.persist(phoneBook);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<PhoneBook> findPhoneBooks(String queryString) {
		StringBuilder queryBuilder = new StringBuilder(" from ");
		queryBuilder.append(PhoneBook.class.getName());

		if (queryString != null) {
			queryBuilder.append(" where lower(name) like :name ");
		}

		Query query = em.createQuery(queryBuilder.toString());

		if (queryString != null) {
			query.setParameter("name", "%" + queryString.toLowerCase() + "%");
		}
		return query.getResultList();
	}

	@Override
	public List<PhoneBook> findPhoneBooks() {
		return findPhoneBooks(null);
	}

	@Override
	public void removePhoneBook(Long phoneBookId) throws RemovalException {
		PhoneBook phoneBook = em.find(PhoneBook.class, phoneBookId);
		if (phoneBook == null) {
			return;
		}
		try {
			em.remove(phoneBook);
			em.flush();
		} catch (PersistenceException e) {
			throw new RemovalException("Failed to remove entity.", phoneBook);
		}
	}

	@Override
	public void updatePhoneBook(PhoneBook phoneBook) {
		em.merge(phoneBook);
	}

	@Override
	public PhoneBook findPhoneBook(Long phoneBookId) {
		return (PhoneBook) em.find(PhoneBook.class, phoneBookId);
	}

	@Override
	public PhoneEntry findPhoneEntry(Long phoneEntryId) {
		return em.find(PhoneEntry.class, phoneEntryId);
	}

	@Override
	public void updatePhoneEntry(PhoneEntry phoneEntry) {
		em.merge(phoneEntry);
	}

}